<template>
  <div class="ivu-date-picker-group-wrap">
    <DatePicker
      ref="start"
      type="date"
      :value="start"
      :options="startDatePickerOptions"
      @on-change="(date, type) => handleChangeDate(date, type, 'start')"
      @on-open-change="isExpand => handleOpenPanel(isExpand, 'start')"
      @on-clear="handleChangeDate('', null, 'start')"
      placeholder="选择开始日期"
      style="margin-right: 10px"
      :capture="false"
      :editable="false"
    ></DatePicker>
    <DatePicker
      ref="end"
      type="date"
      :value="end"
      :options="endDatePickerOptions"
      @on-change="(date, type) => handleChangeDate(date, type, 'end')"
      @on-open-change="isExpand => handleOpenPanel(isExpand, 'end')"
      @on-clear="handleChangeDate('', null, 'end')"
      placeholder="选择结束日期"
      :capture="false"
      :editable="false"
    ></DatePicker>
  </div>
</template>

<script>
export default {
  name: "IvuDatePickerGroup",
  props: {
    startTime: {
      type: String,
      default: ""
    },
    endTime: {
      type: String,
      default: ""
    },
    align: {
      type: String,
      default: "center"
    }
  },
  data() {
    return {
      start: "",
      end: "",
      startDatePickerOptions: {},
      endDatePickerOptions: {}
    };
  },
  watch: {
    startTime: {
      handler(val) {
        this.start = val;
        this.endDatePickerOptions = {
          disabledDate(time) {
            return time.getTime() < new Date(val).getTime();
          }
        };
      },
      immediate: true
    },
    endTime: {
      handler(val) {
        this.end = val;
        this.startDatePickerOptions = {
          disabledDate(time) {
            return time.getTime() > new Date(val).getTime();
          }
        };
      },
      immediate: true
    }
  },
  methods: {
    handleChangeDate(date, dateType, type) {
      let time = "";
      if (date) {
        time = type === "start" ? " 00:00:00" : " 23:59:59";
      }
      this[type] = date + time;
      this.$emit("update:date-range", [this.start, this.end]);
    },

    /* 解决关闭捕获模式时，点击另一个选框，不会取消当前选框focus的问题 */
    handleOpenPanel(isExpand, type) {
      if (isExpand) {
        this.$refs[type].$children[0].$el.children[2].focus();
      }
    }
  }
};
</script>

<style scoped>
.ivu-date-picker-group-wrap {
  width: 300px;
  display: flex;
}
</style>
